import tkinter as tk
from tkinter import ttk,PhotoImage
from PIL import Image,ImageTk

def show_context_menu(event):
    # print('1111')
    context_menu.post(event.x_root, event.y_root)

def get_selected_item():
    selected_item = tree.selection()[0]
    print(tree.selection(),type(tree.selection()))     # 获取选中项,元组类型输出——列表视图按住Ctrl键可以多选
    values = tree.item(selected_item)
    print(values)
    print("选中项的ID：", selected_item)
    print("选中项的值：", values["text"])
    print("选中项的标签：", values["tags"])
    print("选中项的图标：", values["image"])

root = tk.Tk()

context_menu = tk.Menu(root, tearoff=0)     # 创建一个菜单
context_menu.add_command(label="选项1", command=lambda: get_selected_item())
context_menu.add_command(label="选项2", command=lambda: print("选择了选项2"))

tree = ttk.Treeview(root)
tree.pack()

# 添加根级别项
tree.insert("", "end", text="Root Item")

# 添加子项
tree.insert("", "end", text="Child Item")

# 添加具有标签和图标的项
tree.insert("", "end", text="Item with Label", tags=("tag1", "tag2"))
# tree.insert("", "end", text="Item with Label", tags=("tag1", "tag2"), image='icon.png')

button = ttk.Button(root, text="获取选中项的值", command=get_selected_item)
button.pack()


tree.bind('<3>', show_context_menu)
root.mainloop()
